//
//  BKOrderCouponsViewController.m
//  bestkeep
//
//  Created by 马乾征 on 16/11/18.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BKOrderCouponsViewController.h"
#import "BK_OD_Color.h"
#import "BKOrderChooseCouponsCell.h"

NSString *const ODCouponsCodeExchange = @"shopping-tick/userRedeemCodeExchange"; //兑换码兑换
NSString *const ODCCOrderInfoURL = @"order/confirm";

@interface BKOrderCouponsViewController ()
<
    UITableViewDelegate,
    UITableViewDataSource,
    BKOrderExchangeCouponsViewDelegate,
    UIGestureRecognizerDelegate
>
@property(nonatomic, strong)UITableView *tableView;
@property(nonatomic, strong)UIButton *selectBtn;
@property(nonatomic, strong)NSIndexPath *selectedIndexPath;

@property(nonatomic, assign)BOOL keyboardIsVisible;
@property(nonatomic, strong)NSArray <SectionModel *>*dataArray;

@end

@implementation BKOrderCouponsViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    if( ([[[UIDevice currentDevice] systemVersion] doubleValue]>=7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.extendedLayoutIncludesOpaqueBars = NO;
        self.modalPresentationCapturesStatusBarAppearance = NO;
        self.navigationController.navigationBar.clipsToBounds = NO;
    }
    

    
    
    [self initialize];
    [self addKeyboardNotifications];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
        //进入页面 选择适当的优惠券
        if (_cCoupon.coupons.count && _cCoupon.usedCoupon)
        {
            NSInteger index = [_cCoupon.coupons indexOfObject:_cCoupon.usedCoupon];
            _selectedIndexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [_tableView selectRowAtIndexPath:_selectedIndexPath animated:YES scrollPosition:UITableViewScrollPositionNone];
        }
    });
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (void)initialize
{
    self.view.backgroundColor = ThemeBackgroundColor;
    self.navigationItem.title = kOrderLocalizeString(@"BKOrderChooseCoupons");
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:kOrderLocalizeString(@"BKOrderDirectionsForUse") style:UIBarButtonItemStylePlain target:self action:@selector(showDirectionsForUseView)];
    [self.navigationItem.rightBarButtonItem setTintColor:kOrderBlack1];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSFontAttributeName : UIFontNormal} forState:UIControlStateNormal];
    
    _selectBtn = [[UIButton alloc] init];
    [_selectBtn setTitle:@"确定" forState:UIControlStateNormal];
    [_selectBtn setTitleColor:kOrderWhite forState:UIControlStateNormal];
    _selectBtn.layer.cornerRadius = 5;
    _selectBtn.layer.masksToBounds = YES;
    UIImage *btnImage = [Common imageWithFrame:CGRectMake(0, 0, 1, 1) color:kOrderBKGreen];
    [_selectBtn setBackgroundImage:btnImage forState:UIControlStateNormal];
    [_selectBtn addTarget:self action:@selector(usedCoupons:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_selectBtn];
    
    _dataArray = [self creatData];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.backgroundColor = [UIColor clearColor];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    
    BKOrderExchangeCouponsView *exchangeCouponsView = [[BKOrderExchangeCouponsView alloc] initWithFrame:CGRectMake(0, 0, kOrderScreenWidth, 45)];
    exchangeCouponsView.delegate = self;
    _tableView.tableHeaderView = exchangeCouponsView;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hiddenKeyboard:)];
    tap.delegate = self;
    [_tableView addGestureRecognizer:tap];
    
    [self makeConstraints];
    
}

- (void)makeConstraints
{
    [_selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.view).offset(15);
        make.right.mas_equalTo(self.view).offset(-15);
        make.bottom.mas_equalTo(self.view).offset(-10);
        make.height.mas_equalTo(48);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(self.view);
        make.top.mas_equalTo(self.view).offset(0);
        make.bottom.mas_equalTo(_selectBtn.mas_top).offset(-10);
    }];
}

//键盘通知
- (void)addKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)keyboardWillShow:(NSNotification *)nottification
{
    _keyboardIsVisible = YES;
}

- (void)keyboardWillHide:(NSNotification *)nottification
{
    _keyboardIsVisible = NO;
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//tableView 停止编辑
- (void)hiddenKeyboard:(UIGestureRecognizer *)recongnizer
{
    [_tableView endEditing:YES];
}

#pragma mark 手势代理
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    if (_keyboardIsVisible) {
        return YES;
    }
    return NO;
}


//使用优惠券
- (void)usedCoupons:(UIButton *)sender
{

    if (self.block != nil)
    {
        NSInteger index = _selectedIndexPath ? _selectedIndexPath.row : -1;
        BK_orders_dic_order_shoppingTicketList_Model *couponInfo;
        if (index == -1) {
            couponInfo = nil;
        }
        else{
            couponInfo = _cCoupon.coupons[index];
        }
        _cCoupon.usedCoupon = couponInfo;
        self.block((_cCoupon));
    }
    [self.navigationController popViewControllerAnimated:YES];
}
//兑换优惠券
- (void)orderViewExchangeCoupons:(NSString *)code
{
    __weak typeof(self)weakSelf = self;
    
    kOrderLoading;
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(ODCouponsCodeExchange) parameters:@{@"code" : code} success:^(id  _Nullable responseObject) {
        BOOL success = [responseObject[@"success"] boolValue];
        if (!success) {
            kOrderDismiss;
            kOrderPromptMsg(responseObject[@"msg"]);
            return;
        }
        NSArray *tickets = responseObject[@"data"][@"couponList"];
        [weakSelf requestOrderInfoWithTickets:tickets];
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        kOrderDismiss;
        NSString *errorMsg;
        if (error.code == -1009) {
            errorMsg = @"请求超时";
        }
        else{
            errorMsg = @"请求失败";
        }
        kOrderPromptMsg(errorMsg);
    }];
}

//请求订单详情
- (void)requestOrderInfoWithTickets:(NSArray *)tickets
{
    __weak typeof(self)weakSelf = self;
    NSMutableDictionary *paramMutableDic = [NSMutableDictionary dictionaryWithDictionary:_orderParamDic];
    [paramMutableDic setObject:tickets forKey:@"tickets"];

    NSString *paramJSONString = [paramMutableDic mj_JSONString];
    
    [[RequestManager manager] bkDataRequest:RequestMethodPost URLString:kOrderURL(ODCCOrderInfoURL) parameters:@{@"data" : paramJSONString} success:^(id  _Nullable responseObject) {
        kOrderDismiss;
        BOOL success = [responseObject[@"success"] boolValue];
        if (!success) {
            kOrderPromptMsg(responseObject[@"msg"]);
            return;
        }
        NSArray *orders = responseObject[@"data"][@"orders"];
        for (NSDictionary *orderInfoDic in orders) {
            NSArray *shoppingTicketList = orderInfoDic[@"shoppingTicketList"];
            NSMutableArray *couponsMArr = [NSMutableArray array];
            
            BKOrderCurrentCoupon *cCoupon = [[BKOrderCurrentCoupon alloc] init];
            
            for (int i = 0; i < shoppingTicketList.count; i++) {
                NSDictionary *couponDic = shoppingTicketList[i];
                BK_orders_dic_order_shoppingTicketList_Model *couponInfo = [BK_orders_dic_order_shoppingTicketList_Model mj_objectWithKeyValues:couponDic];
                if ([couponInfo.selected boolValue]) {
                    cCoupon.usedCoupon = couponInfo;
                }
                [couponsMArr addObject:couponInfo];
            }
            cCoupon.coupons = couponsMArr.copy;
            _cCoupon = cCoupon;
            _dataArray = [weakSelf creatData];
            [_tableView reloadData];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_MSEC)), dispatch_get_main_queue(), ^{
                NSInteger index = [couponsMArr indexOfObject:_cCoupon.usedCoupon];
                [_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
            });
        }
        kOrderSuccessMsg(@"兑换成功");
        
    } failure:^(id  _Nullable responseObject, NSError * _Nullable error) {
        kOrderDismiss;
        NSString *errorMsg;
        if (error.code == -1001) {
            errorMsg = @"请求超时";
        }
        else{
            errorMsg = @"请求失败";
        }
        kOrderPromptMsg(errorMsg);
    }];
}

- (NSArray<SectionModel *> *)creatData
{
    NSMutableArray <SectionModel *>*data = [NSMutableArray array];
    
    NSMutableArray <CellModel *>*cellArray = [NSMutableArray array];
    if (_cCoupon.coupons.count)
    {
        for (BK_orders_dic_order_shoppingTicketList_Model *coupon in _cCoupon.coupons)
        {
            CellModel *cm = [[CellModel alloc] init];
            cm.className = NSStringFromClass([BKOrderCouponsCell class]);
            cm.reuseIdentifier = @"couponsCell";
            cm.height = [BKOrderCouponsCell computeHeight:coupon];
            cm.selectorString = @"couponCellDidSelected:";
            cm.userInfo = coupon;
            [cellArray addObject:cm];
        }
        
        SectionModel *sm = [SectionModel sectionModelWithTitle:nil cells:cellArray.copy];
        sm.reuseIdentifier = @"couponsHeader";
        sm.className = NSStringFromClass([BKOrderCCHeaderView class]);
        sm.userInfo = @"说明：已自动为您匹配以下优惠券";
        sm.headerhHeight = [BKOrderCCHeaderView computeHeight:sm.userInfo];
        sm.footerHeight = 0.1;
        [data addObject:sm];
        
        _selectBtn.hidden = NO;
    }
    else
    {
        CellModel *cm = [[CellModel alloc] init];
        cm.className = NSStringFromClass([BKOrderCouponsNullCell class]);
        cm.reuseIdentifier = @"nullCouponsCell";
        cm.height = [BKOrderCouponsNullCell computeHeight:nil];
        cm.selectorString = @"nullCellDidSelected:";
        
        SectionModel *sm = [SectionModel sectionModelWithTitle:nil cells:@[cm]];
        sm.headerhHeight = 0.1;
        sm.footerHeight = 0.1;
        [data addObject:sm];
        
        _selectBtn.hidden = YES;
    }
    return data.copy;
}

#pragma mark table 代理相关
/**
    section
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (!_dataArray) {
        return 0;
    }
    return _dataArray.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    SectionModel *sm = _dataArray[section];
    BKOrderChooseCouponsHFView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:sm.reuseIdentifier];
    if (!headerView) {
        headerView = [[NSClassFromString(sm.className) alloc] initWithReuseIdentifier:sm.reuseIdentifier];
    }
    return headerView;
}

- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    SectionModel *sm = _dataArray[section];
    BKOrderChooseCouponsHFView *headerView = (BKOrderChooseCouponsHFView *)view;
    
    SEL selector = @selector(fillData:);
    if ([headerView respondsToSelector:selector]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [headerView performSelector:selector withObject:sm.userInfo];
        #pragma clang diagnostic pop
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    SectionModel *sm = _dataArray[section];
    return sm.headerhHeight;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    SectionModel *sm = _dataArray[section];
    return sm.footerHeight;
}

/**
    cell
 */
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SectionModel *sm = _dataArray[section];
    return sm.cells.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel *sm = _dataArray[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    return cm.height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel *sm = _dataArray[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    BKOrderChooseCouponsCell *cell = [tableView dequeueReusableCellWithIdentifier:cm.reuseIdentifier];
    if(!cell) {
        cell = [[NSClassFromString(cm.className) alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cm.reuseIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    SectionModel *sm = _dataArray[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    BKOrderCouponsCell *cCell = (BKOrderCouponsCell *)cell;
    
    SEL selector = @selector(fillData:);
    if ([cCell respondsToSelector:selector]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [cCell performSelector:selector withObject:cm.userInfo];
        #pragma clang diagnostic pop
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    SectionModel *sm = _dataArray[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    
    SEL selector = NSSelectorFromString(cm.selectorString);
    if (selector && [self respondsToSelector:selector]) {
        #pragma clang diagnostic push
        #pragma clang diagnostic ignored"-Warc-performSelector-leaks"
        [self performSelector:selector withObject:indexPath];
        #pragma clang diagnostic pop
    }
    
}

// 优惠券cell 点击
- (void)couponCellDidSelected:(NSIndexPath *)indexPath
{
    SectionModel *sm = _dataArray[indexPath.section];
    CellModel *cm = sm.cells[indexPath.row];
    BK_orders_dic_order_shoppingTicketList_Model *couponInfo = cm.userInfo;
    
    if ([couponInfo.canUseFlag boolValue] == NO) {
        NSInteger index = [_cCoupon.coupons indexOfObject:_cCoupon.usedCoupon];
        [_tableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionNone];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该优惠券不适用于此订单" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertView show];
        return;
    }
    
    if ([_selectedIndexPath isEqual:indexPath]) {
        [_tableView deselectRowAtIndexPath:indexPath animated:YES];
        _selectedIndexPath = nil;
        return;
    }
    _selectedIndexPath = indexPath;
}

//null  cell  点击
- (void)nullCellDidSelected:(NSIndexPath *)indexPath
{
    _selectedIndexPath = nil;
}
#pragma mark 显示使用说明view

- (void)showDirectionsForUseView
{
    [_tableView endEditing:YES];
    BKOrderDirectionsForUseView * directionsForUseView = [[BKOrderDirectionsForUseView alloc] init];
    [directionsForUseView showInView:self.navigationController.view];
}



@end
